/*
 * Copyright 2005-2013 biz-united. All rights reserved.
 * Support: http://www.biz-united.com.cn
 * License: http://www.biz-united.com.cn/?page_id=5&act=3
 */
package net.biz.controller.admin;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.biz.Message;
import net.biz.Page;
import net.biz.Pageable;
import net.biz.dto.OrderDTO;
import net.biz.dto.ProductDto;
import net.biz.entity.Admin;
import net.biz.entity.Area;
import net.biz.entity.Brand;
import net.biz.entity.DeliveryCorp;
import net.biz.entity.Member;
import net.biz.entity.Order;
import net.biz.entity.Order.OrderStatus;
import net.biz.entity.Order.PaymentStatus;
import net.biz.entity.Order.ShippingStatus;
import net.biz.entity.OrderItem;
import net.biz.entity.Payment;
import net.biz.entity.Payment.Status;
import net.biz.entity.Payment.Type;
import net.biz.entity.PaymentMethod;
import net.biz.entity.Product;
import net.biz.entity.Refunds;
import net.biz.entity.Returns;
import net.biz.entity.ReturnsItem;
import net.biz.entity.Shipping;
import net.biz.entity.ShippingItem;
import net.biz.entity.ShippingMethod;
import net.biz.entity.Sn;
import net.biz.service.AdminService;
import net.biz.service.AreaService;
import net.biz.service.DeliveryCorpService;
import net.biz.service.OrderItemService;
import net.biz.service.OrderService;
import net.biz.service.PaymentMethodService;
import net.biz.service.ProductService;
import net.biz.service.ShippingMethodService;
import net.biz.service.SnService;
import net.biz.util.JsonUtils;
import net.biz.util.ParamsUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.home766.dto.PaymentDTO;
import com.home766.entity.Dictionary;
import com.home766.entity.SchemeProduct;
import com.home766.entity.Shops;
import com.home766.service.IDictionaryService;
import com.home766.service.SchemeProductService;
import com.home766.service.ShopsService;
import com.home766.util.DateTime;
import com.home766.util.PaymentUtil;
import com.home766.util.StringUtil;
import com.home766.util.poi.excel.BrowserUtils;
import com.home766.util.poi.excel.ExcelExportUtil;
import com.home766.util.poi.excel.entity.vo.ExcelTitle;

/**
 * Controller - 订单
 * 
 * @author BIZ Team
 * @version 3.0
 */
@Controller("adminOrderController")
@RequestMapping("/admin/order")
public class OrderController extends BaseController {

	@Resource(name = "adminServiceImpl")
	private AdminService adminService;
	@Resource(name = "areaServiceImpl")
	private AreaService areaService;
	@Resource(name = "productServiceImpl")
	private ProductService productService;
	@Resource(name = "orderServiceImpl")
	private OrderService orderService;
	@Resource(name = "orderItemServiceImpl")
	private OrderItemService orderItemService;
	@Resource(name = "shippingMethodServiceImpl")
	private ShippingMethodService shippingMethodService;
	@Resource(name = "deliveryCorpServiceImpl")
	private DeliveryCorpService deliveryCorpService;
	@Resource(name = "paymentMethodServiceImpl")
	private PaymentMethodService paymentMethodService;
	@Resource(name = "snServiceImpl")
	private SnService snService;
	@Resource(name = "schemeProductServiceImpl")
	private SchemeProductService schemeProductServiceImpl;
	@Resource(name="shopsServiceImpl")
	private ShopsService shopsService;
	@Autowired
	private IDictionaryService dictionaryServiceImpl;
	/**
	 * 检查锁定
	 */
	@RequestMapping(value = "/check_lock", method = RequestMethod.POST)
	public @ResponseBody
	Message checkLock(Long id) {
		Order order = orderService.find(id);
		if (order == null) {
			return Message.warn("admin.common.invalid");
		}
		Admin admin = adminService.getCurrent();
		if (order.isLocked(admin)) {
			if (order.getOperator() != null) {
				return Message.warn("admin.order.adminLocked", order.getOperator().getUsername());
			} else {
				return Message.warn("admin.order.memberLocked");
			}
		} else {
			order.setLockExpire(DateUtils.addSeconds(new Date(), 20));
			order.setOperator(admin);
			orderService.update(order);
			return SUCCESS_MESSAGE;
		}
	}

	/**
	 * 查看
	 */
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public String view(Long id, ModelMap model) {
		model.addAttribute("methods", Payment.Method.values());
		model.addAttribute("refundsMethods", Refunds.Method.values());
		model.addAttribute("paymentMethods", paymentMethodService.findAll());
		model.addAttribute("shippingMethods", shippingMethodService.findAll());
		model.addAttribute("deliveryCorps", deliveryCorpService.findAll());
		model.addAttribute("order", orderService.find(id));
		return "/admin/order/view";
	}

	/**
	 * 确认
	 */
	@RequestMapping(value = "/confirm", method = RequestMethod.POST)
	public String confirm(Long id, RedirectAttributes redirectAttributes) {
		Order order = orderService.find(id);
		Admin admin = adminService.getCurrent();
		if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed && !order.isLocked(admin)) {
			orderService.confirm(order, admin);
			addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		} else {
			addFlashMessage(redirectAttributes, Message.warn("admin.common.invalid"));
		}
		return "redirect:view.jhtml?id=" + id;
	}

	/**
	 * 完成
	 */
	@RequestMapping(value = "/complete", method = RequestMethod.POST)
	public String complete(Long id, RedirectAttributes redirectAttributes) {
		Order order = orderService.find(id);
		Admin admin = adminService.getCurrent();
		if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.confirmed && !order.isLocked(admin)) {
			orderService.complete(order, admin);
			addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		} else {
			addFlashMessage(redirectAttributes, Message.warn("admin.common.invalid"));
		}
		return "redirect:view.jhtml?id=" + id;
	}

	/**
	 * 取消
	 */
	@RequestMapping(value = "/cancel", method = RequestMethod.POST)
	public String cancel(Long id, RedirectAttributes redirectAttributes) {
		Order order = orderService.find(id);
		Admin admin = adminService.getCurrent();
		if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed && !order.isLocked(admin)) {
			orderService.cancel(order, admin);
			addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		} else {
			addFlashMessage(redirectAttributes, Message.warn("admin.common.invalid"));
		}
		return "redirect:view.jhtml?id=" + id;
	}

	/**
	 * 支付
	 */
	@RequestMapping(value = "/payment", method = RequestMethod.POST)
	public String payment(Long orderId, Long paymentMethodId, Payment payment, RedirectAttributes redirectAttributes) {
		Order order = orderService.find(orderId);
		payment.setOrder(order);
		PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
		payment.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
		if (!isValid(payment)) {
			return ERROR_VIEW;
		}
		if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed) {
			return ERROR_VIEW;
		}
		if (order.getPaymentStatus() != PaymentStatus.unpaid && order.getPaymentStatus() != PaymentStatus.partialPayment) {
			return ERROR_VIEW;
		}
		if (payment.getAmount().compareTo(new BigDecimal(0)) <= 0 || payment.getAmount().compareTo(order.getAmountPayable()) > 0) {
			return ERROR_VIEW;
		}
		Member member = order.getMember();
		if (payment.getMethod() == Payment.Method.deposit && payment.getAmount().compareTo(member.getBalance()) > 0) {
			return ERROR_VIEW;
		}
		Admin admin = adminService.getCurrent();
		if (order.isLocked(admin)) {
			return ERROR_VIEW;
		}
		payment.setSn(snService.generate(Sn.Type.payment));
		payment.setType(Type.payment);
		payment.setStatus(Status.success);
		payment.setFee(new BigDecimal(0));
		payment.setOperator(admin.getUsername());
		payment.setPaymentDate(new Date());
		payment.setPaymentPluginId(null);
		payment.setExpire(null);
		payment.setDeposit(null);
		payment.setMember(null);
		orderService.payment(order, payment, admin);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:view.jhtml?id=" + orderId;
	}

	/**
	 * 退款
	 */
	@RequestMapping(value = "/refunds", method = RequestMethod.POST)
	public String refunds(Long orderId, Long paymentMethodId, Refunds refunds, RedirectAttributes redirectAttributes) {
		Order order = orderService.find(orderId);
		refunds.setOrder(order);
		PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
		refunds.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
		if (!isValid(refunds)) {
			return ERROR_VIEW;
		}
		if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed) {
			return ERROR_VIEW;
		}
		if (order.getPaymentStatus() != PaymentStatus.paid && order.getPaymentStatus() != PaymentStatus.partialPayment && order.getPaymentStatus() != PaymentStatus.partialRefunds) {
			return ERROR_VIEW;
		}
		if (refunds.getAmount().compareTo(new BigDecimal(0)) <= 0 || refunds.getAmount().compareTo(order.getAmountPaid()) > 0) {
			return ERROR_VIEW;
		}
		Admin admin = adminService.getCurrent();
		if (order.isLocked(admin)) {
			return ERROR_VIEW;
		}
		refunds.setSn(snService.generate(Sn.Type.refunds));
		refunds.setOperator(admin.getUsername());
		orderService.refunds(order, refunds, admin);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:view.jhtml?id=" + orderId;
	}

	/**
	 * 发货
	 */
	@RequestMapping(value = "/shipping", method = RequestMethod.POST)
	public String shipping(Long orderId, Long shippingMethodId, Long deliveryCorpId, Long areaId, Shipping shipping,String engineering, RedirectAttributes redirectAttributes) {
		Order order = orderService.find(orderId);
		if (order == null) {
			return ERROR_VIEW;
		}
		order.setEngineering(engineering);
		Shops shops=order.getServiceShops();
		if(shops==null||(shops!=null&&shops.getId()==null)){
			shops=orderService.serviceShopOrder(order.getSn());
			order.setServiceShops(shops);
		}
		orderService.updateServiceShop(order.getId(), shops);
		order.setShippingStatus(ShippingStatus.shipped);
		orderService.update(order);
		for (Iterator<ShippingItem> iterator = shipping.getShippingItems().iterator(); iterator.hasNext();) {
			ShippingItem shippingItem = iterator.next();
			if (shippingItem == null || StringUtils.isEmpty(shippingItem.getSn()) || shippingItem.getQuantity() == null || shippingItem.getQuantity() <= 0) {
				iterator.remove();
				continue;
			}
			OrderItem orderItem = order.getOrderItem(shippingItem.getSn());
			if (orderItem == null || shippingItem.getQuantity() > orderItem.getQuantity() - orderItem.getShippedQuantity()) {
				return ERROR_VIEW;
			}
			if (orderItem.getProduct() != null && orderItem.getProduct().getStock() != null && shippingItem.getQuantity() > orderItem.getProduct().getStock()) {
				return ERROR_VIEW;
			}
			shippingItem.setName(orderItem.getFullName());
			shippingItem.setShipping(shipping);
		}
		shipping.setOrder(order);
		ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
		shipping.setShippingMethod(shippingMethod != null ? shippingMethod.getName() : null);
		DeliveryCorp deliveryCorp = deliveryCorpService.find(deliveryCorpId);
		shipping.setDeliveryCorp(deliveryCorp != null ? deliveryCorp.getName() : null);
		shipping.setDeliveryCorpUrl(deliveryCorp != null ? deliveryCorp.getUrl() : null);
		shipping.setDeliveryCorpCode(deliveryCorp != null ? deliveryCorp.getCode() : null);
		Area area = areaService.find(areaId);
		shipping.setArea(area != null ? area.getFullName() : null);
		if (!isValid(shipping)) {
			return ERROR_VIEW;
		}
		if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed) {
			return ERROR_VIEW;
		}
/*		if (order.getShippingStatus() != ShippingStatus.unshipped && order.getShippingStatus() != ShippingStatus.partialShipment) {
			return ERROR_VIEW;
		}*/
		Admin admin = adminService.getCurrent();
		if (order.isLocked(admin)) {
			return ERROR_VIEW;
		}
		shipping.setSn(snService.generate(Sn.Type.shipping));
		shipping.setOperator(admin.getUsername());
		orderService.shipping(order, shipping, admin);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:view.jhtml?id=" + orderId;
	}

	/**
	 * 退货
	 */
	@RequestMapping(value = "/returns", method = RequestMethod.POST)
	public String returns(Long orderId, Long shippingMethodId, Long deliveryCorpId, Long areaId, Returns returns, RedirectAttributes redirectAttributes) {
		Order order = orderService.find(orderId);
		if (order == null) {
			return ERROR_VIEW;
		}
		for (Iterator<ReturnsItem> iterator = returns.getReturnsItems().iterator(); iterator.hasNext();) {
			ReturnsItem returnsItem = iterator.next();
			if (returnsItem == null || StringUtils.isEmpty(returnsItem.getSn()) || returnsItem.getQuantity() == null || returnsItem.getQuantity() <= 0) {
				iterator.remove();
				continue;
			}
			OrderItem orderItem = order.getOrderItem(returnsItem.getSn());
			if (orderItem == null || returnsItem.getQuantity() > orderItem.getShippedQuantity() - orderItem.getReturnQuantity()) {
				return ERROR_VIEW;
			}
			returnsItem.setName(orderItem.getFullName());
			returnsItem.setReturns(returns);
		}
		returns.setOrder(order);
		ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
		returns.setShippingMethod(shippingMethod != null ? shippingMethod.getName() : null);
		DeliveryCorp deliveryCorp = deliveryCorpService.find(deliveryCorpId);
		returns.setDeliveryCorp(deliveryCorp != null ? deliveryCorp.getName() : null);
		Area area = areaService.find(areaId);
		returns.setArea(area != null ? area.getFullName() : null);
		if (!isValid(returns)) {
			return ERROR_VIEW;
		}
		if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed) {
			return ERROR_VIEW;
		}
		if (order.getShippingStatus() != ShippingStatus.shipped && order.getShippingStatus() != ShippingStatus.partialShipment && order.getShippingStatus() != ShippingStatus.partialReturns) {
			return ERROR_VIEW;
		}
		Admin admin = adminService.getCurrent();
		if (order.isLocked(admin)) {
			return ERROR_VIEW;
		}
		returns.setSn(snService.generate(Sn.Type.returns));
		returns.setOperator(admin.getUsername());
		orderService.returns(order, returns, admin);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:view.jhtml?id=" + orderId;
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id,Integer msg, ModelMap model) {
		model.addAttribute("msg", msg);
		model.addAttribute("paymentMethods", paymentMethodService.findAll());
		model.addAttribute("shippingMethods", shippingMethodService.findAll());
		model.addAttribute("order", orderService.find(id));
		return "/admin/order/edit";
	}

	/**
	 * 订单项添加
	 */
	@RequestMapping(value = "/order_item_add", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> orderItemAdd(String productSn) {
		Map<String, Object> data = new HashMap<String, Object>();
		Product product = productService.findBySn(productSn);
		if (product == null) {
			data.put("message", Message.warn("admin.order.productNotExist"));
			return data;
		}
		if (!product.getIsMarketable()) {
			data.put("message", Message.warn("admin.order.productNotMarketable"));
			return data;
		}
		if (product.getIsOutOfStock()) {
			data.put("message", Message.warn("admin.order.productOutOfStock"));
			return data;
		}
		data.put("sn", product.getSn());
		data.put("fullName", product.getFullName());
		data.put("name", product.getName());
		data.put("price", product.getPrice());
		data.put("weight", product.getWeight());
		data.put("isGift", product.getIsGift());
		Brand brand= product.getBrand();
		if(null!=brand){
			data.put("brandName", brand.getName());
		}else{
			data.put("brandName", " ");
		}
		data.put("message", SUCCESS_MESSAGE);
		return data;
	}
	/**
	 * 订单项添加
	 */
	@RequestMapping(value = "/order_item_add_scheme", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> orderItemAddScheme(String schemeSn,Long orderId,Long orderItemId,Integer num,Integer area) {
		if(num==null){
			num=1;
		}
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			SchemeProduct schemeProduct = schemeProductServiceImpl.findBySn(schemeSn);
			if (schemeProduct == null) {
				data.put("message", Message.warn("admin.order.productNotExist"));
				return data;
			}
			Order order=orderService.find(orderId);
			if(order==null){
				data.put("message", Message.warn("admin.order.productNotExist"));
				return data;
			}
			BigDecimal price=schemeProduct.getPrice();
			if(orderItemId!=null){
				OrderItem oi=orderItemService.find(orderItemId);
				Dictionary dt=dictionaryServiceImpl.find(schemeProduct.getNameId());
				BigDecimal coefficient=new BigDecimal("1");
				
				BigDecimal sysDiffPrice=new BigDecimal("0.00");
				BigDecimal doubleDiffPrice=new BigDecimal("0.00");
				boolean isCalculate=true;
				if(dt.getChildrens()!=null&&dt.getChildrens().size()>0){
					String tempCoefficient=dt.getChildrens().get(0).getTitle();
					coefficient=new BigDecimal(tempCoefficient);
//					Integer area= order.getSchemeArea();
					Integer schemeArea=order.getSchemeArea();
					Integer totalArea=area+schemeArea;//页面总面积
					price=coefficient.multiply(price).multiply(new BigDecimal(totalArea));
					Integer oldShopArea= order.getShopSchemeArea();
					if(null==oldShopArea){
						oldShopArea=0;
					}
					Integer oldArea=order.getSchemeArea();
					Integer oldTotalArea=oldShopArea+oldArea;//方案总面积
					BigDecimal  iniOIPrice=oi.getPrice().multiply(new BigDecimal(oldTotalArea)).multiply(coefficient);
					sysDiffPrice=price.subtract(iniOIPrice);//差价
					
					BigDecimal temp=oi.getDifferencePrice();
					
					if(temp!=null){
						temp=temp.multiply(new BigDecimal(oldTotalArea)).multiply(coefficient);
						//得到差价额度
						doubleDiffPrice=sysDiffPrice.subtract(temp);
					}else{
						doubleDiffPrice=sysDiffPrice;
					}
//					doubleDiffPrice=sysDiffPrice.subtract(iniOIPrice);
//					doubleDiffPrice=doubleDiffPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
//					if(sysDiffPrice.compareTo(iniOIPrice)==0){
//						isCalculate=false;
//					}
				}else{
					Integer iniQuantity=oi.getIniQuantity();//初始数量
					BigDecimal iniPrice=oi.getSchemeProductPrice();//初始单价
					//num当前数量
					BigDecimal newPrice=schemeProduct.getPrice();
					sysDiffPrice=(newPrice.multiply(new BigDecimal(num))).subtract(iniPrice.multiply(new BigDecimal(iniQuantity)));
					if(sysDiffPrice.compareTo(oi.getDifferencePrice())==0){
						isCalculate=false;
					}
					doubleDiffPrice=sysDiffPrice;
				}
				data.put("isCalculate", isCalculate);
				data.put("coefficient", coefficient);
				data.put("sysDiffPrice", sysDiffPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
				data.put("doubleDiffPrice", doubleDiffPrice);
			}
			data.put("sn", schemeProduct.getSn());
			data.put("name", schemeProduct.getName());
			data.put("fullName", schemeProduct.getName());
			data.put("brandName", schemeProduct.getBrand().getName());
			data.put("thumbnail", schemeProduct.getImage());
			
			data.put("price", price);
			data.put("quantity", 1);
			data.put("orderType", 2);
			data.put("differencePrice", "0.00");
			data.put("isShopAdd", true);
			data.put("specificationValue", schemeProduct.getSpecificationValue().getName());
			
			data.put("weight", 0);
			data.put("isGift", false);
			data.put("message", SUCCESS_MESSAGE);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return data;
	}

	/**
	 * 计算
	 */
	@RequestMapping(value = "/calculate", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> calculate(Order order, Long areaId, Long paymentMethodId, Long shippingMethodId) {
		Map<String, Object> data = new HashMap<String, Object>();
		for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();) {
			OrderItem orderItem = iterator.next();
			if (orderItem == null || StringUtils.isEmpty(orderItem.getSn())) {
				iterator.remove();
			}
		}
		order.setArea(areaService.find(areaId));
		order.setPaymentMethod(paymentMethodService.find(paymentMethodId));
		order.setShippingMethod(shippingMethodService.find(shippingMethodId));
//		if (!isValid(order)) {
//			data.put("message", Message.warn("admin.common.invalid"));
//			return data;
//		}
		Order pOrder = orderService.find(order.getId());
		if (pOrder == null) {
			data.put("message", Message.error("admin.common.invalid"));
			return data;
		}
		for (OrderItem orderItem : order.getOrderItems()) {
			if (orderItem.getId() != null) {
				OrderItem pOrderItem = orderItemService.find(orderItem.getId());
				if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder())) {
					data.put("message", Message.error("admin.common.invalid"));
					return data;
				}
				Product product = pOrderItem.getProduct();
				if (product != null && product.getStock() != null) {
					if (pOrder.getIsAllocatedStock()) {
						if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity()) {
							data.put("message", Message.warn("admin.order.lowStock"));
							return data;
						}
					} else {
						if (orderItem.getQuantity() > product.getAvailableStock()) {
							data.put("message", Message.warn("admin.order.lowStock"));
							return data;
						}
					}
				}
			} else {
				Product product = productService.findBySn(orderItem.getSn());
				if (product == null) {
					data.put("message", Message.error("admin.common.invalid"));
					return data;
				}
				if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock()) {
					data.put("message", Message.warn("admin.order.lowStock"));
					return data;
				}
			}
		}
		Map<String, Object> orderItems = new HashMap<String, Object>();
		for (OrderItem orderItem : order.getOrderItems()) {
			orderItems.put(orderItem.getSn(), orderItem);
		}
		order.setFee(pOrder.getFee());
		order.setPromotionDiscount(pOrder.getPromotionDiscount());
		order.setCouponDiscount(pOrder.getCouponDiscount());
		order.setAmountPaid(pOrder.getAmountPaid());
		data.put("weight", order.getWeight());
		data.put("price", order.getPrice());
		data.put("quantity", order.getQuantity());
		data.put("amount", order.getAmount());
		data.put("orderItems", orderItems);
		data.put("message", SUCCESS_MESSAGE);
		return data;
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Order order, Long areaId, Long paymentMethodId, Long shippingMethodId, RedirectAttributes redirectAttributes) {
		for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();) {
			OrderItem orderItem = iterator.next();
			if (orderItem == null || StringUtils.isEmpty(orderItem.getSn())) {
				iterator.remove();
			}
		}
		Order pOrder = orderService.find(order.getId());
		if (pOrder == null) {
			return ERROR_VIEW;
		}
		order.setArea(areaService.find(areaId));
		order.setPaymentMethod(paymentMethodService.find(paymentMethodId));
		order.setShippingMethod(shippingMethodService.find(shippingMethodId));
		order.setIsInvoice(pOrder.getIsInvoice());
		if (!isValid(order)) {
			return ERROR_VIEW;
		}
		if(pOrder.getOrderType()==ParamsUtil.CART_TYPE_SCHEME){
			return "redirect:edit.jhtml?id="+pOrder.getId()+"&msg="+ParamsUtil.CART_TYPE_NORMAL;
		}
		if (pOrder.isExpired() || pOrder.getOrderStatus() != OrderStatus.unconfirmed) {
			return ERROR_VIEW;
		}
		order.setIsInvoice(pOrder.getIsInvoice());
		order.setInvoice(pOrder.getInvoice());
		order.setInvoiceTitle(pOrder.getInvoiceTitle());
		order.setInvoiceType(pOrder.getInvoiceType());
		Admin admin = adminService.getCurrent();
		if (pOrder.isLocked(admin)) {
			return ERROR_VIEW;
		}
		if (!order.getIsInvoice()) {
			order.setInvoiceTitle(null);
			order.setTax(new BigDecimal(0));
		}
		for (OrderItem orderItem : order.getOrderItems()) {
			if (orderItem.getId() != null) {
				OrderItem pOrderItem = orderItemService.find(orderItem.getId());
				if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder())) {
					return ERROR_VIEW;
				}
				Product product = pOrderItem.getProduct();
				if (product != null && product.getStock() != null) {
					if (pOrder.getIsAllocatedStock()) {
						if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity()) {
							return ERROR_VIEW;
						}
					} else {
						if (orderItem.getQuantity() > product.getAvailableStock()) {
							return ERROR_VIEW;
						}
					}
				}
				BeanUtils.copyProperties(pOrderItem, orderItem, new String[] { "price", "quantity" });
				if (pOrderItem.getIsGift()) {
					orderItem.setPrice(new BigDecimal(0));
				}
			} else {
				Product product = productService.findBySn(orderItem.getSn());
				if (product == null) {
					return ERROR_VIEW;
				}
				if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock()) {
					return ERROR_VIEW;
				}
				orderItem.setName(product.getName());
				orderItem.setFullName(product.getFullName());
				if (product.getIsGift()) {
					orderItem.setPrice(new BigDecimal(0));
				}
				orderItem.setWeight(product.getWeight());
				orderItem.setThumbnail(product.getThumbnail());
				orderItem.setIsGift(product.getIsGift());
				orderItem.setShippedQuantity(0);
				orderItem.setReturnQuantity(0);
				orderItem.setProduct(product);
				orderItem.setOrder(pOrder);
			}
		}
		order.setSn(pOrder.getSn());
		order.setOrderStatus(pOrder.getOrderStatus());
		order.setPaymentStatus(pOrder.getPaymentStatus());
		order.setShippingStatus(pOrder.getShippingStatus());
		order.setFee(pOrder.getFee());
		order.setPromotionDiscount(pOrder.getPromotionDiscount());
		order.setCouponDiscount(pOrder.getCouponDiscount());
		order.setAmountPaid(pOrder.getAmountPaid());
		order.setPromotion(pOrder.getPromotion());
		order.setExpire(pOrder.getExpire());
		order.setLockExpire(null);
		order.setIsAllocatedStock(pOrder.getIsAllocatedStock());
		order.setOperator(null);
		order.setMember(pOrder.getMember());
		order.setCouponCode(pOrder.getCouponCode());
		order.setCoupons(pOrder.getCoupons());
		order.setOrderLogs(pOrder.getOrderLogs());
		order.setDeposits(pOrder.getDeposits());
		order.setPayments(pOrder.getPayments());
		order.setRefunds(pOrder.getRefunds());
		order.setShippings(pOrder.getShippings());
		order.setReturns(pOrder.getReturns());

		orderService.update(order, admin);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Shops shops,Date beginDate,Date endDate,Integer schemeStatus,Integer schemePaymentStatus,Integer orderType,OrderStatus orderStatus, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired, Pageable pageable, ModelMap model) {
		Admin admin = adminService.getCurrent();
		shops = shopsService.getSingleShops(admin.getId());
		String propertiesValue = pageable.getSearchValue();
		String properties = pageable.getSearchProperty();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(beginDate != null){
			model.addAttribute("beginDate", sdf.format(beginDate));
		}else{
			model.addAttribute("beginDate", null);
		}
		if(endDate != null){
			model.addAttribute("endDate", sdf.format(endDate));
		}else{
			model.addAttribute("endDate", null);
		}
		model.addAttribute("shops", shops);
		model.addAttribute("orderStatus", orderStatus);
		model.addAttribute("paymentStatus", paymentStatus);
		model.addAttribute("shippingStatus", shippingStatus);
		model.addAttribute("hasExpired", hasExpired);
		model.addAttribute("schemeStatus", schemeStatus);
		model.addAttribute("orderType", orderType);
		model.addAttribute("propertiesValue",propertiesValue);
		model.addAttribute("properties",properties);
		model.addAttribute("admin",admin);
		Page<Order> page = orderService.findPage(shops,admin.getId(),beginDate,endDate,schemeStatus,schemePaymentStatus,ParamsUtil.CART_TYPE_NORMAL,orderStatus, paymentStatus, shippingStatus, hasExpired, pageable,null,null,null,null,null,false);
		model.addAttribute("page",page);
		return "/admin/order/list";
	}
	

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	Message delete(Long[] ids) {
		if (ids != null) {
			Admin admin = adminService.getCurrent();
			for (Long id : ids) {
				Order order = orderService.find(id);
				if (order != null && order.isLocked(admin)) {
					return Message.error("admin.order.deleteLockedNotAllowed", order.getSn());
				}
			}
			orderService.delete(ids);
		}
		return SUCCESS_MESSAGE;
	}

	/**
	 * 更新方案
	 */
	@RequestMapping(value = "/updateScheme")
	public String updateScheme(Order order, Long areaId, Long paymentMethodId, Long shippingMethodId, RedirectAttributes redirectAttributes,Boolean _isInvoice,String update_order_item_schemes) {
		if(order!=null){
			if(null==order.getIsInvoice()){
				order.setIsInvoice(false);
			}
			if(null==order.getOffsetAmount()){
				order.setOffsetAmount(new BigDecimal(0));
			}
		}
		for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();) {
			OrderItem orderItem = iterator.next();
			if (orderItem == null || StringUtils.isEmpty(orderItem.getSn())) {
				iterator.remove();
			}
		}
		Order pOrder = orderService.find(order.getId());
		if (pOrder == null) {
			return ERROR_VIEW;
		}
		order.setSchemeName(pOrder.getSchemeName());
		order.setIsTehui(pOrder.getIsTehui());
		order.setIsChange(pOrder.getIsChange());
		order.setBeginArea(pOrder.getBeginArea());
		order.setEndArea(pOrder.getEndArea());
		order.setSchemeSn(pOrder.getSchemeSn());
		order.setSchemeImage(pOrder.getSchemeImage());
		order.setRewardPoint(pOrder.getRewardPoint());
		order.setPercent(pOrder.getPercent());
		order.setPaymentTimes(pOrder.getPaymentTimes());
//		boolean isCalculateArea=false;
//		Integer tempShopSchemeArea=order.getShopSchemeArea();
//		Integer tempSchemeArea=pOrder.getSchemeArea();
//		Integer tempOldArea=pOrder.getShopSchemeArea();
//		if(tempOldArea==null){
//			tempOldArea=0;
//		}
//		if(tempShopSchemeArea==null){
//			tempShopSchemeArea=0;
//		}
//		if(tempShopSchemeArea!=tempOldArea){
//			isCalculateArea=true;
//		}
//		Integer tempTotalArea=tempShopSchemeArea+tempSchemeArea;
//		Integer tempTotalAreaOld=tempOldArea+tempSchemeArea;
		if(pOrder.getSchemeStatus()==ParamsUtil.SCHEME_STATUS_HEADQUARTERS){
//			String contract=order.getContract();
			String memo=order.getMemo();
			String engineering=order.getEngineering();
			BeanUtils.copyProperties(pOrder, order);
//			order.setContract(contract);
			if(!StringUtil.isNullOrSpace(memo)){
				order.setMemo(memo);
			}
			if(!StringUtil.isNullOrSpace(engineering)){
				order.setEngineering(engineering);
			}
			shippingMethodId=pOrder.getShippingMethod().getId();
			areaId=pOrder.getArea().getId();
			paymentMethodId=pOrder.getPaymentMethod().getId();
		}
		
		order.setIsInvoice(pOrder.getIsInvoice());
		order.setInvoice(pOrder.getInvoice());
		order.setInvoiceTitle(pOrder.getInvoiceTitle());
		order.setInvoiceType(pOrder.getInvoiceType());
		//室内机
		order.setInNumber(pOrder.getInNumber());
		//室外机
		order.setOutNumber(pOrder.getOutNumber());
		order.setSchemeType(pOrder.getSchemeType());
		order.setArea(areaService.find(areaId));
		order.setPaymentMethod(paymentMethodService.find(paymentMethodId));
		order.setShippingMethod(shippingMethodService.find(shippingMethodId));
		if (!isValid(order)) {
			return ERROR_VIEW;
		}
		
		if (pOrder.isExpired() || pOrder.getSchemeStatus() ==ParamsUtil.SCHEME_STATUS_CANSEL||pOrder.getSchemeStatus() ==ParamsUtil.SCHEME_STATUS_COMPLETE) {
			return ERROR_VIEW;
		}
		//没有首次支付概念，去掉之前的首次支付比例限制
/*		if(order.getPercent().compareTo(new BigDecimal(ParamsUtil.ORDER_PAY_PERCENT_UPDATE))<0){
			return ERROR_VIEW;
		}*/
		Admin admin = adminService.getCurrent();
		if (pOrder.isLocked(admin)) {
			return ERROR_VIEW;
		}
		if (!order.getIsInvoice()) {
			order.setInvoiceTitle(null);
			order.setTax(new BigDecimal(0));
		}
		order.setSchemeArea(pOrder.getSchemeArea());//方案面积
		List<Map<String, Object>> editList=new ArrayList<Map<String, Object>>();
		if(!StringUtil.isNullOrSpace(update_order_item_schemes)){
			editList=JsonUtils.toObject(update_order_item_schemes, List.class);
		}
		for (OrderItem orderItem : order.getOrderItems()) {
			if(orderItem.getIsGift()==null||(orderItem.getIsGift()!=null&&!orderItem.getIsGift())){
				if(orderItem.getId()==null){
					SchemeProduct schemeProduct=schemeProductServiceImpl.findBySn(orderItem.getSn());
					if (schemeProduct == null) {
						return ERROR_VIEW;
					}
					orderItem.setName(schemeProduct.getName());
					orderItem.setFullName(schemeProduct.getName());
					orderItem.setPrice(schemeProduct.getPrice());
					orderItem.setWeight(0);
					orderItem.setThumbnail(schemeProduct.getImage());
					orderItem.setIsGift(false);
					orderItem.setShippedQuantity(0);
					orderItem.setReturnQuantity(0);
					orderItem.setProduct(null);
					
					orderItem.setSchemeNameId(schemeProduct.getNameId());
					orderItem.setSchemeImage(schemeProduct.getImage());
					orderItem.setSchemeProductBrand(schemeProduct.getBrand().getName());
					orderItem.setSchemeProductName(schemeProduct.getName());
					orderItem.setSchemeProductPrice(schemeProduct.getPrice());
					orderItem.setSchemeProductSn(schemeProduct.getSn());
					orderItem.setSchemeProductSpecificationValue(schemeProduct.getSpecificationValue().getName());
					
					
					
					orderItem.setIsShopAdd(true);
					orderItem.setShopSchemeImage(schemeProduct.getImage());
					orderItem.setShopSchemeProductBrand(schemeProduct.getBrand().getName());
					orderItem.setShopSchemeProductName(schemeProduct.getName());
					orderItem.setShopSchemeProductPrice(schemeProduct.getPrice());
					orderItem.setShopSchemeProductSn(schemeProduct.getSn());
					orderItem.setShopSchemeProductSpecificationValue(schemeProduct.getSpecificationValue().getName());
					
					
					
					orderItem.setDifferencePrice(new BigDecimal("0.00"));
					orderItem.setOrder(pOrder);
					orderItem.setOrderType(ParamsUtil.CART_TYPE_SCHEME);
				}else{
					boolean isBool=false;
					OrderItem pOrderItem = orderItemService.find(orderItem.getId());//根据ID 查询
					Integer quantity=orderItem.getQuantity();//获取数量
					if(editList.size()>0){
						for(Map<String,Object> map:editList){
							Long id=Long.parseLong(String.valueOf(map.get("key")));
							if(id.longValue()==orderItem.getId().longValue()){
								Long schemeProductId=Long.parseLong(String.valueOf(map.get("value")));
								BeanUtils.copyProperties(pOrderItem, orderItem);
								SchemeProduct newSp= schemeProductServiceImpl.find(schemeProductId);//正在替换的主材
								BigDecimal tempPrice=new BigDecimal("0.00");//差价
								BigDecimal oldPrice= orderItem.getSchemeProductPrice();//原始价格
								BigDecimal newPrice=newSp.getPrice();
								
								BigDecimal coefficient=pOrderItem.getCoefficient();
								if(coefficient!=null){
//									tempPrice=newPrice.subtract(oldPrice);
//									Integer area= order.getSchemeArea();
//									Integer shopArea=order.getShopSchemeArea();
//									if(shopArea==null){
//										shopArea=pOrder.getShopSchemeArea();
//									}
//									Integer totalArea=area+shopArea;
//									
//									newPrice=coefficient.multiply(newPrice).multiply(new BigDecimal(totalArea));
//									quantity=1;
								}else{
									oldPrice=oldPrice.multiply(new BigDecimal(orderItem.getIniQuantity()));
									newPrice=newPrice.multiply(new BigDecimal(quantity));
								}
								tempPrice=newPrice.subtract(oldPrice);
								orderItem.setQuantity(quantity);
								
								orderItem.setShopSchemeProductPrice(newSp.getPrice());
								orderItem.setShopSchemeProductName(newSp.getName());
								orderItem.setShopSchemeProductBrand(newSp.getBrand().getName());
								orderItem.setShopSchemeProductSn(newSp.getSn());
								orderItem.setShopSchemeProductSpecificationValue(newSp.getSpecificationValue().getName());
								orderItem.setDifferencePrice(tempPrice);
								orderItem.setSchemeNameId(newSp.getNameId());
								orderItem.setIsShopAdd(true);
								isBool=true;
								break;
							}
						}
					}
					if(!isBool){
						BeanUtils.copyProperties(pOrderItem, orderItem);
						BigDecimal tempPrice=new BigDecimal("0.00");//差价
						BigDecimal oldPrice= orderItem.getSchemeProductPrice();
						BigDecimal newPrice=orderItem.getPrice();
						if(orderItem.getShopSchemeProductPrice()!=null){
							newPrice=orderItem.getShopSchemeProductPrice();
						}
						
						BigDecimal coefficient=pOrderItem.getCoefficient();
						if(coefficient==null){
							oldPrice=oldPrice.multiply(new BigDecimal(orderItem.getIniQuantity()));
							newPrice=newPrice.multiply(new BigDecimal(quantity));
							tempPrice=newPrice.subtract(oldPrice);
							orderItem.setDifferencePrice(tempPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
						}else{
//							if(isCalculateArea){
////								BigDecimal newCoeffPrice= orderItem.getCoefficientPrice().multiply(new BigDecimal(tempTotalArea)).multiply(coefficient);
////								orderItem.setShopSchemeProductPrice(newCoeffPrice);
////								orderItem.setDifferencePrice(newCoeffPrice.subtract(orderItem.getSchemeProductPrice()));
//							}
							quantity=1;
						}
						orderItem.setQuantity(quantity);
					}
				}
			}else{
				//赠品
				Product product = productService.findBySn(orderItem.getSn());
				if (product == null) {
					return ERROR_VIEW;
				}
				if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock()) {
					return ERROR_VIEW;
				}
				orderItem.setName(product.getName());
				orderItem.setFullName(product.getFullName());
				if (product.getIsGift()) {
					orderItem.setPrice(new BigDecimal(0));
				}
				orderItem.setWeight(product.getWeight());
				orderItem.setThumbnail(product.getThumbnail());
				orderItem.setIsGift(product.getIsGift());
				orderItem.setShippedQuantity(0);
				orderItem.setReturnQuantity(0);
				orderItem.setProduct(product);
				orderItem.setOrder(pOrder);
			}
		}
		order.setOrderType(ParamsUtil.CART_TYPE_SCHEME);
		order.setExpire(null);
		order.setSn(pOrder.getSn());
		order.setOrderStatus(pOrder.getOrderStatus());
		order.setPaymentStatus(pOrder.getPaymentStatus());
		order.setShippingStatus(pOrder.getShippingStatus());
		order.setFee(pOrder.getFee());
		order.setPromotionDiscount(pOrder.getPromotionDiscount());
		order.setCouponDiscount(pOrder.getCouponDiscount());
		order.setAmountPaid(pOrder.getAmountPaid());
		order.setPromotion(pOrder.getPromotion());
		order.setExpire(pOrder.getExpire());
		order.setLockExpire(null);
		order.setIsAllocatedStock(pOrder.getIsAllocatedStock());
		order.setOperator(null);
		order.setMember(pOrder.getMember());
		order.setCouponCode(pOrder.getCouponCode());
		order.setCoupons(pOrder.getCoupons());
		order.setOrderLogs(pOrder.getOrderLogs());
		order.setDeposits(pOrder.getDeposits());
		order.setPayments(pOrder.getPayments());
		order.setRefunds(pOrder.getRefunds());
		order.setShippings(pOrder.getShippings());
		order.setReturns(pOrder.getReturns());
		order.setSchemeType(pOrder.getSchemeType());
		if(StringUtil.isNullOrSpace(order.getAddress())){
			order.setAddress(pOrder.getAddress());
		}
		//设置当前订单原数据
		order.setIsCustomerPay(pOrder.getIsCustomerPay());//是否门店支付
		order.setPercentPrice(pOrder.getPercentPrice());//客户应支付
		order.setPercentPricePaid(pOrder.getPercentPricePaid());//客户已支付
		order.setIsShopPay(pOrder.getIsShopPay());//是否门店支付
		order.setShopShouldPay(pOrder.getShopShouldPay());//门店应支付
		order.setShopPaid(pOrder.getShopPaid());//门店已支付
		
		order.setInstallCost(pOrder.getInstallCost());//安装费
		order.setAuxiliaryUnitPrice(pOrder.getAuxiliaryUnitPrice());//辅材
		order.setIsCustomerPay(pOrder.getIsCustomerPay());//客户是否已支付
		order.setIsShopPay(pOrder.getIsShopPay());//门店是否已支付
		order.setSchemeStatus(pOrder.getSchemeStatus());//方案状态
		if(order.getShopSchemeArea()==null||(order.getShopSchemeArea()==null&& order.getShopSchemeArea()==0)){
			order.setShopSchemeArea(pOrder.getShopSchemeArea());//门店调整面积
		}
		if(StringUtil.isNullOrSpace(order.getEngineering())){
			order.setEngineering(pOrder.getEngineering());//工程编号
		}
		if(StringUtil.isNullOrSpace(order.getContract())){
			order.setContract(pOrder.getContract());//合同编号
			
		}
		order.setSchemePaymentStatus(pOrder.getSchemePaymentStatus());//支付状态
		
		if(order.getSchemeStatus()==ParamsUtil.SCHEME_STATUS_STORE){
/*			if(order.getPercent().compareTo(new BigDecimal(ParamsUtil.ORDER_PAY_PERCENT_UPDATE))<0){
				order.setPercent(pOrder.getPercent());//支付比例
			}
		}else{*/
			order.setPercent(pOrder.getPercent());
		}
		if(StringUtil.isNullOrSpace(order.getCommunity())){
			order.setCommunity(pOrder.getCommunity()); //小区
		}
		if(StringUtil.isNullOrSpace(order.getHouseType())){
			order.setHouseType(pOrder.getHouseType()); //户型
		}
		order.setBackCuse(pOrder.getBackCuse());//退回原因
		order.setCanselCause(pOrder.getCanselCause());//取消原因
/*		BigDecimal tempTotal= order.getAmount();//订单总价
		BigDecimal tempPercent= order.getPercent().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);//
		BigDecimal tempCustomerPay= tempTotal.multiply(tempPercent);
		BigDecimal shopPay=tempTotal.subtract(tempCustomerPay);
		if(order.getSchemePaymentStatus()==ParamsUtil.SCHEME_PAYMENT_STATUS_UNPAID&&order.getSchemeStatus()<ParamsUtil.SCHEME_STATUS_PAY){
			//客户未支付
			order.setPercentPrice(tempCustomerPay);
			order.setShopShouldPay(shopPay);//门店应支付
		}else if(order.getSchemePaymentStatus()==ParamsUtil.SCHEME_PAYMENT_STATUS_PARTIALPAYMENT&&order.getSchemeStatus()>ParamsUtil.SCHEME_STATUS_PAY){
			BigDecimal percentPricePaid=pOrder.getPercentPricePaid();//客户已支付
			BigDecimal shopShouldPay=tempTotal.subtract(percentPricePaid);//门店应支付
			order.setShopShouldPay(shopShouldPay);
		}*/
		Shops shops=order.getServiceShops();
		if(shops==null||(shops!=null&&shops.getId()==null)){
			if(order.getSchemeStatus()==ParamsUtil.SCHEME_STATUS_HEADQUARTERS || order.getSchemeStatus()==ParamsUtil.SCHEME_STATUS_ACCEPTANCE){
				shops=orderService.serviceShop(order.getSn());
				order.setServiceShops(shops);
			}
		}
		orderService.updateServiceShop(order.getId(), shops);
		orderService.update(order, admin);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:listScheme.jhtml";
	}
	/**
	 * 查看
	 */
	@RequestMapping(value = "/viewScheme", method = RequestMethod.GET)
	public String viewScheme(Long id, ModelMap model) {
		model.addAttribute("methods", Payment.Method.values());
		model.addAttribute("refundsMethods", Refunds.Method.values());
		model.addAttribute("paymentMethods", paymentMethodService.findAll());
		model.addAttribute("shippingMethods", shippingMethodService.findAll());
		model.addAttribute("deliveryCorps", deliveryCorpService.findAll());
		Order order = orderService.find(id);
		model.addAttribute("order", order);
		return "/admin/order/viewScheme";
	}
	/**
	 * 列表
	 */
	@RequestMapping(value = "/listScheme", method = RequestMethod.GET)
	public String listScheme(Shops shops,Date beginDate,Date endDate,Integer schemeStatus,Integer schemePaymentStatus,Integer orderType,OrderStatus orderStatus, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired, Pageable pageable, ModelMap model) {
		Admin admin = adminService.getCurrent();
		shops = shopsService.getSingleShops(admin.getId());
		String propertiesValue = pageable.getSearchValue();
		String properties = pageable.getSearchProperty();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(beginDate != null){
			model.addAttribute("beginDate", sdf.format(beginDate));
		}else{
			model.addAttribute("beginDate", null);
		}
		if(endDate != null){
			model.addAttribute("endDate", sdf.format(endDate));
		}else{
			model.addAttribute("endDate", null);
		}
		model.addAttribute("shops", shops);
		model.addAttribute("orderStatus", orderStatus);
		model.addAttribute("paymentStatus", paymentStatus);
		model.addAttribute("shippingStatus", shippingStatus);
		model.addAttribute("hasExpired", hasExpired);
		model.addAttribute("schemeStatus", schemeStatus);
		model.addAttribute("schemeStatus", schemeStatus);
		model.addAttribute("schemePaymentStatus", schemePaymentStatus);
		model.addAttribute("propertiesValue",propertiesValue);
		model.addAttribute("properties",properties);
		model.addAttribute("page", orderService.findPage(shops,admin.getId(),beginDate,endDate,schemeStatus,schemePaymentStatus,ParamsUtil.CART_TYPE_SCHEME,orderStatus, paymentStatus, shippingStatus, hasExpired, pageable,null,null,null,null,null,false));
		return "/admin/order/listScheme";
	}
	/**
	 * 编辑
	 */
	@RequestMapping(value = "/editScheme", method = RequestMethod.GET)
	public String editScheme(Long id,Integer msg, ModelMap model) {
		model.addAttribute("msg", msg);
		model.addAttribute("paymentMethods", paymentMethodService.findAll());
		model.addAttribute("shippingMethods", shippingMethodService.findAll());
		model.addAttribute("order", orderService.find(id));
		return "/admin/order/editScheme";
	}
	/**
	 * ajax scheme
	 */
	@ResponseBody
	@RequestMapping(value = "/showScheme", method = RequestMethod.GET)
	public String showSchemeOrderItems(Long id) {
		Order order= orderService.find(id);
		List<OrderItem> orderItems=order.getOrderItems();
		String str=JsonUtils.toJson(orderItems);
		return str;
	}
	/***
	 * 审批/尾款
	 * @param id
	 * @param staffType
	 * @param backCuse
	 * @return
	 */
	@RequestMapping(value="/upateSchemeStatus")
	public String updateSchemeStatus(Long id,Integer staffType,String backCuse){
		Order o=orderService.find(id);
		if(backCuse!=null){
			o.setBackCuse(backCuse);
		}
		Integer oldStatus=null;
		Integer newStatus=null;
		if(ParamsUtil.SCHEME_STAFF_TYPE==staffType){
			oldStatus=o.getSchemeStatus();
			if(oldStatus!=ParamsUtil.SCHEME_STATUS_CANSEL||oldStatus==ParamsUtil.SCHEME_STATUS_COMPLETE){
				if(oldStatus==ParamsUtil.SCHEME_STATUS_STORE_BACK_HEADQUARTERS||oldStatus==ParamsUtil.SCHEME_STATUS_STORE_BACK_ACCEPTANCE){
					newStatus=ParamsUtil.SCHEME_STATUS_HEADQUARTERS;
				}else{
					newStatus=oldStatus+1;
				}
			}
		}else{
			oldStatus=o.getSchemeStatus();
			if(oldStatus==ParamsUtil.SCHEME_STATUS_HEADQUARTERS){
				newStatus=ParamsUtil.SCHEME_STATUS_STORE_BACK_HEADQUARTERS;
			}else{
				newStatus=ParamsUtil.SCHEME_STATUS_STORE_BACK_ACCEPTANCE;
			}
		}
		//审批通过后推送服务门店
		Shops shops=o.getServiceShops();
		if(shops==null||(shops!=null&&shops.getId()==null)){
			if(o.getSchemeStatus()==ParamsUtil.SCHEME_STATUS_HEADQUARTERS){
				shops=orderService.serviceShop(o.getSn());
				o.setServiceShops(shops);
			}
		}
		orderService.updateServiceShop(o.getId(), shops);
		try {
			orderService.updateSchemeStatus(oldStatus, newStatus, o,staffType,getCurrent());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "redirect:viewScheme.jhtml?id="+o.getId();
	}
	/**
	 * 取消订单
	 * @param id
	 * @param canselCause
	 * @return
	 */
	@RequestMapping(value="/cancelScheme")
	public String cancelScheme(Long id,String canselCause){
		if(StringUtil.isNullOrSpace(canselCause)){
			return "/admin/order/viewScheme";
		}
		Order o=orderService.find(id);
		Integer oldStatus=o.getSchemeStatus();
		Integer newStatus=ParamsUtil.SCHEME_STATUS_CANSEL;
		o.setCanselCause(canselCause);
		orderService.updateSchemeStatus(oldStatus, newStatus, o,ParamsUtil.SCHEME_STAFF_TYPE,getCurrent());
		return "redirect:viewScheme.jhtml?id="+o.getId();
	}
	@ResponseBody
	@RequestMapping(value="/updateOrderItem",method=RequestMethod.GET,produces=("text/plain; charset=utf-8"))
	public String updateOrderItem(Long id,Long edit){
		if(id!=null&&edit!=null){
			return orderService.updateOrderItem(id, edit);
		}
		return null;
	}
	
	@ResponseBody
	@RequestMapping(value="/searchByCategory",method=RequestMethod.GET,produces=("text/plain; charset=utf-8"))
	public String searchByCategory(Long categoryId){
		List<SchemeProduct> list= schemeProductServiceImpl.findByCategory(categoryId,true);
		String str=JsonUtils.toJson(list);
		return str;
	}
	@ResponseBody
	@RequestMapping(value="/searchSchemeProduct",method=RequestMethod.GET,produces=("text/plain; charset=utf-8"))
	public String searchSchemeProduct(Long type,String sn,String name){
		List<SchemeProduct> list= schemeProductServiceImpl.findSchemeProductByType(type, sn, name);
		String str=JsonUtils.toJson(list);
		return str;
	}
	@RequestMapping("/exportXlsOrderInfo")
	public void exportXlsOrderInfo(Shops shops,Date beginDate,Date endDate,Integer schemeStatus,Integer orderType,OrderStatus orderStatus, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired,HttpServletRequest request,HttpServletResponse response){
		Admin admin = adminService.getCurrent();
		if(admin.getUsername().equals("admin")){
			admin = new Admin();
		}
		response.setContentType("application/vnd.ms-excel");
		String codedFileName = null;
		OutputStream fOut = null;
		List<OrderDTO> exporList= new ArrayList<OrderDTO>();
		Pageable pagebale = new Pageable();
		pagebale.setSearchProperty(request.getParameter("searchProperty"));
		pagebale.setSearchValue(request.getParameter("searchValue"));
		if(orderType==1){
			exporList=orderService.getOrderList(shops,admin.getId(),beginDate,endDate,schemeStatus,ParamsUtil.CART_TYPE_NORMAL, orderStatus, paymentStatus, shippingStatus, hasExpired,pagebale);
			codedFileName = "导出单品订单信息";
		}else{
			exporList=orderService.getOrderList(shops,admin.getId(),beginDate,endDate,schemeStatus,ParamsUtil.CART_TYPE_SCHEME, orderStatus, paymentStatus, shippingStatus, hasExpired,pagebale);
			codedFileName = "导出方案订单信息";
		}
		try {
			// 根据浏览器进行转码，使其支持中文文件名
			if (BrowserUtils.isIE(request)) {
				response.setHeader(
						"content-disposition",
						"attachment;filename="
								+ java.net.URLEncoder.encode(codedFileName,
										"UTF-8") + ".xls");
			} else {
				String newtitle = new String(codedFileName.getBytes("UTF-8"),
						"ISO8859-1");
				response.setHeader("content-disposition",
						"attachment;filename=" + newtitle + ".xls");
			}
			// 产生工作簿对象
			HSSFWorkbook workbook = null;
			workbook = ExcelExportUtil.exportExcel(new ExcelTitle(codedFileName, "导出人:"+adminService.getCurrentUsername(),
					"导出信息"), OrderDTO.class, exporList);
			fOut = response.getOutputStream();
			workbook.write(fOut);
		} catch (Exception e) {
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	/**
	 * 支付
	 */
	@RequestMapping(value = "/tlpayment", method = RequestMethod.GET)
	public String tlpayment(String sn,String token,BigDecimal paymentAmount,HttpServletRequest request, ModelMap model) {
		Order order = orderService.findBySn(sn);
		Member member= order.getMember();
		PaymentDTO dto=new PaymentDTO();
		dto.setPayerName(member.getName());//名称
		dto.setPayerEmail(member.getEmail());//邮箱
		dto.setPayerTelephone(order.getPhone());//联系人电话
		if(order.getPaymentTimes()==null){
			order.setPaymentTimes(0);
		}else{
			order.setPaymentTimes(order.getPaymentTimes()+1);
		}
		dto.setOrderNo(order.getSn());//订单编号
		if(order.getOrderType()==ParamsUtil.CART_TYPE_SCHEME&&order.getSchemePaymentStatus()==ParamsUtil.SCHEME_PAYMENT_STATUS_PARTIALPAYMENT){
			dto.setOrderNo(order.getSn()+"-"+order.getPaymentTimes().toString());//订单编号(虚拟订单尾数由支付次数构成)
		}
		BigDecimal temp=paymentAmount==null?order.getAmount():paymentAmount;
		temp=temp.multiply(new BigDecimal("100"));
		temp=temp.setScale(0, BigDecimal.ROUND_HALF_UP); 
		dto.setOrderAmount(String.valueOf(temp));//应支付金额
		dto.setOrderDatetime(DateTime.timeToString(new Date()));//商户订单提交时间
		dto.setOrderExpireDatetime("5");//过期时间 order.getExpire()+""
		dto.setProductNum(String.valueOf(order.getQuantity()));
		dto.setProductDesc(order.getMemo());
		if(order.getOrderType()==ParamsUtil.CART_TYPE_NORMAL){
			dto.setProductName("766智能家商城单品订单");
			//常规商品
		}else{
			dto.setProductName("766智能家商城方案订单");
			//方案
		}
		PaymentUtil.getParams(dto,null);//028 6687983       15928898607 
		model.addAttribute("order",order);
		model.addAttribute("pay",dto);
		model.addAttribute("paymentAmount",paymentAmount);
		return "/admin/order/payment";
	}
	/**
	 * 检查支付
	 */
	@RequestMapping(value = "/check_payment", method = RequestMethod.POST)
	public @ResponseBody
	boolean checkPayment(String sn) {
		Order order = orderService.findBySn(sn);
		if(order.getOrderType()==ParamsUtil.CART_TYPE_SCHEME){
			if(order != null && order.getSchemePaymentStatus() == ParamsUtil.SCHEME_PAYMENT_STATUS_PAID){
				return true;
			}
		}
		return false;
	}
	@ResponseBody
	@RequestMapping(value="/searchProductList",method=RequestMethod.POST,produces=("text/plain; charset=utf-8"))
	public String searchProductList(String name,String sn,Pageable pageable){
		if(pageable==null){
			pageable=new Pageable(1, 1000);
		}else{
			pageable=new Pageable(1, 1000);
		}
		Page<ProductDto> page=null;
		page= productService.searchProductListForGift(name, sn, pageable);
		String str=JsonUtils.toJson(page.getContent());
		return str;
	}
}